Telegram Group & Telegram Channel
🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.



tg-me.com/pro_python_code/1804
Create:
Last Update:

🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1804

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

NEWS: Telegram supports Facetime video calls NOW!

Secure video calling is in high demand. As an alternative to Zoom, many people are using end-to-end encrypted apps such as WhatsApp, FaceTime or Signal to speak to friends and family face-to-face since coronavirus lockdowns started to take place across the world. There’s another option—secure communications app Telegram just added video calling to its feature set, available on both iOS and Android. The new feature is also super secure—like Signal and WhatsApp and unlike Zoom (yet), video calls will be end-to-end encrypted.

Python RU from it


Telegram Python RU
FROM USA